

import { useEffect, useState,useCallback,useMemo,memo,useRef, use} from "react"
import home from '../Home.module.less'
import {updateResumeItem} from '../../../api/index.js'


const ContentBox = memo (({
    inputType, 
    contentValue, 
    isEdit,
    label,
    name
})=>{
    console.log('box render')
    const [value,setValue] = useState(contentValue)
   
    useEffect(()=>{
        setValue(contentValue)
    },[contentValue])
    
    return (
        <>
            {label}
            {/* 查看状态 */}
            {!isEdit && (value)} 
            
            {/* 编辑状态 */}
            { isEdit  && (
                inputType === 'textarea' ? 
                <textarea  
                name={name}
                    style={{position:'relative',width:'100%',minWidth:'80%', maxWith:'100%', flex:'1 s1'}}
                    defaultValue= { value }  
                    type="text" 
                />   :

              <input  
                name={name}
                defaultValue= { value }  
                type="text" 
              /> 

            )}
        </>
    )
})


const LoopEditModel  = memo(({
    inputType,
    isEdit,
    modelValue, //当前模块的内容
    propertyAttr, //当前模块的所属键名
})=>{
    
    const [modelContent,setModelContent] = useState(modelValue  || [])

    // 批量 删除
    const handleDelEduOrSkillItem =(id)=>{
        let list = [...modelContent]
        let result = list.filter(item=>item.id !== id)
        setModelContent(result)
    }
    
    // 批量 新增
    const handleAddEduOrSkilItem =(objKey)=>{
        switch(objKey){
            case 'educationExperience': {
                // 变量必须在循环内，不能提取为公共变量
                let oldData = Object.assign([],modelContent)
                let oldId = oldData?.[oldData.length - 1]?.id || 0
                oldData.push({
                    id:oldId + 1,
                    time:'时间',
                    school:'学校',
                    additional:[
                        {
                            id:1,
                            name:'附加说明'
                        }
                    ]
                })
                setModelContent(oldData)
                break;
            }

            case 'professionalSkill': {
                let oldData = Object.assign([],modelContent)
                let oldId = oldData?.[oldData.length - 1]?.id || 0
                oldData.push({
                    id:oldId+1,
                    name:'技能++'
                })
                setModelContent(oldData)
                break
            }

            case 'workExperience' : {
                let oldData = Object.assign([],modelContent)
                let oldId = oldData?.[oldData.length - 1]?.id || 0
                oldData.push({
                    id:oldId + 1,
                    time:'时间',
                    company:'公司',
                    position:'职位',
                    additional:[
                        {
                            id:1,
                            name:'具体内容'
                        }
                    ]
                })
                setModelContent(oldData)
                break
            }
            case 'openProduct': {
                let oldData = Object.assign([],modelContent)
                let oldId = oldData?.[oldData.length - 1]?.id || 0
                oldData.push({
                    id:oldId + 1,
                    time:'时间',
                    projectName:'项目名称',
                    position:'角色',
                    constent:'介绍'
                })
                setModelContent(oldData)
                break
            }
        }
    }


    // 删除 子项
    const handleDeleteEducationDesc=(eduIdx,descId)=>{
        let oldEducationExperience = Object.assign([], modelContent)
        let finalAdditional = oldEducationExperience?.[eduIdx]?.additional.filter((item)=>item.id !== descId)
        oldEducationExperience[eduIdx].additional = finalAdditional
        setModelContent(oldEducationExperience)
    }

    // 子项 新增
    const handleAddEducationDesc = (index)=> {
        let oldEducationExperience = [...modelContent]
        let length = oldEducationExperience?.[index]?.additional?.length || undefined
        let oldId = oldEducationExperience?.[index]?.additional?.[length-1]?.id || 0

        oldEducationExperience?.[index]?.additional.push(
            {
                id:oldId + 1,
                name:''
            }
        )
        setModelContent(oldEducationExperience)
    }


    return (
        <div className={home.loopEditModel}>
        {
           modelContent?.length > 0  
            && modelContent?.map((childItem,childIdx)=>{
                return (
                    <div key={childItem.id} className={home.childBox}>
                        {
                            propertyAttr !== 'professionalSkill' && isEdit &&
                            (<div style={{display:'flex',justifyContent:'flex-end'}}>
                                <div onClick={()=>handleDelEduOrSkillItem(childItem.id)} className={home.deleteEduItemBtn}>—</div>
                            </div>)
                        }

                        { 
                            propertyAttr !== 'professionalSkill' &&
                            <div  className={home.modelHeader}>
                                <span >
                                    <ContentBox 
                                        name={`${propertyAttr}_${childIdx}_time`}
                                        contentValue={modelContent[childIdx].time} 
                                        isEdit={isEdit}
                                    />
                                </span>
                                <span >
                                    <ContentBox 
                                        name={`${propertyAttr}_${childIdx}_` + 
                                                (propertyAttr === 'educationExperience' ? 
                                                    'school' : 
                                                    ( propertyAttr === 'workExperience' ? 'company' : 'projectName'))
                                            }
                                        contentValue={
                                            modelContent[childIdx][propertyAttr === 'educationExperience' ? 
                                                    'school' : 
                                                    ( propertyAttr === 'workExperience' ? 'company' : 'projectName')]
                                        } 
                                        isEdit={isEdit}
                                    />
                                </span>
                            </div>
                        }

                        {  (propertyAttr === 'workExperience' || propertyAttr === 'openProduct')  &&
                            <div style={{display:"flex",flexDirection:'row',justifyContent:'flex-start'}}>
                                <ContentBox 
                                    name={`${propertyAttr}_${childIdx}_position`}
                                    contentValue={modelContent[childIdx].position} 
                                    isEdit={isEdit}
                                />
                            </div>
                        }

                        {  
                            (propertyAttr === 'professionalSkill' || propertyAttr === 'openProduct') &&
                            <div key={childItem.id} className={home.professionalSkillModel}>
                                <ContentBox 
                                    name={`${propertyAttr}_${childIdx}_` + 
                                            (propertyAttr === 'professionalSkill' ? 
                                                'name' : 
                                                'content')
                                        }
                                    contentValue={modelContent[childIdx][ propertyAttr === 'professionalSkill' ? 'name' : 'content']} 
                                    isEdit={isEdit}
                                    inputType={inputType}
                                />
                                {
                                  propertyAttr === 'professionalSkill' &&  isEdit && <div onClick={()=>handleDelEduOrSkillItem(childItem.id)} className={home.deleteDescBtn}>—</div>
                                }
                                
                            </div>
                        }

                        {
                            propertyAttr !== 'professionalSkill' && 
                            propertyAttr !== 'openProduct'  &&
                            <ul>
                                {
                                    childItem?.additional?.length > 0  && childItem?.additional?.map((additionItm,additionIdx)=>{
                                        return (
                                            <li key={additionItm.id}>
                                                <ContentBox 
                                                    name={`${propertyAttr}_${childIdx}_additional_${additionIdx}_name`}
                                                    inputType={inputType}
                                                    contentValue={modelContent[childIdx].additional[additionIdx].name} 
                                                    isEdit={isEdit}
                                                />

                                                {
                                                    isEdit && <div onClick={()=>handleDeleteEducationDesc(childIdx,additionItm.id)} className={home.deleteDescBtn}>—</div>
                                                }

                                                
                                            </li>
                                        )
                                    })
                                }

                                {
                                    isEdit && <li onClick={()=>handleAddEducationDesc(childIdx)}>新增</li>
                                }
                                
                            </ul>
                        }
                    </div>
                )
            })
        }

        {
            isEdit && <div onClick={()=>handleAddEduOrSkilItem(propertyAttr)}>新增</div>
        }

    </div>
    )

})

export default  function ResumeContent({
    id,
    resumeList,
    updateResume,
    changeEditFlag
}){
    
    useEffect(()=>{
        resumeList.map(item=>{
            if(item.id === id){
                setDetailPersonalMessage(item.content)
            }
        })
    },[id,resumeList])


    const contentForm =  useRef(null)
    const [isEdit,setIsEdit] = useState()
    const [detailPersonalMessage,setDetailPersonalMessage] = useState({
        name:'姓名',
        sex:'',
        age:null,
        telephone:'',
        presentAddress:'',
        email:'',
        nation:'',
        intendedPosition:'',
        intendedCity:'',
        intendedSalary:'',
        jobApplicationType:'',
        currentStatus:'',
        educationExperience:[
            {
                id:1,
                time:'时间',
                school:'学校',
                additional:[
                    {
                        id:1,
                        name:'附加说明'
                    },
                ]
            }
        ],
        professionalSkill:[
            {
                id:1,
                name:'技能1'
            }
        ],
        workExperience:[
            {
                id:1,
                time:'时间',
                company:'公司',
                position:'职位',
                additional:[
                    {
                        id:1,
                        
                        name:'具体内容',
                    }
                ]
            }
        ],
        openProduct:[
            {
                id:1,
                time:'时间',
                projectName:'项目名称',
                position:'角色',
                content:'内容'
            }
        ]
    })

    // 编辑简历
    const resumeEdit=()=>{
        setIsEdit(true)
        changeEditFlag(id)
    }

    // 取消编辑
    const cancelResumeEdit=()=>{
        setIsEdit(false)
        changeEditFlag()
    }

    // 保存简历
    const resumeSave = (newContent)=>{
        resumeList.map(async item=>{
            if(item.id === id){
                // 调用接口修改信息
                await updateResumeItem({...item,content:newContent})
            }
        })
        updateResume()
        setIsEdit(false)
        changeEditFlag()
    }

    // 表单提交
    const handleSubmit=(e)=>{
        e.preventDefault();
        // 读取表单数据
        const formData = new FormData(e.target);
        let list = new Map(formData.entries());

        // 处理表单数据
        let newResumeContent = {}
        list.forEach((value,key)=>{
            let keys = key.split('_')
            if(keys[1] !== undefined){
                newResumeContent[keys[0]] = newResumeContent[keys[0]] || []
                if(keys[3] !== undefined){
                    newResumeContent[keys[0]][keys[1]] = newResumeContent[keys[0]][keys[1]] || {}
                    newResumeContent[keys[0]][keys[1]][keys[2]] = newResumeContent[keys[0]][keys[1]][keys[2]] || []
                    newResumeContent[keys[0]][keys[1]][keys[2]][keys[3]] = newResumeContent[keys[0]][keys[1]][keys[2]][keys[3]] || {}
                    newResumeContent[keys[0]][keys[1]][keys[2]][keys[3]][keys[4]] = value
                }else{
                    newResumeContent[keys[0]][keys[1]] = newResumeContent[keys[0]][keys[1]] || {}
                    newResumeContent[keys[0]][keys[1]][keys[2]] =value
                }
            }else{
                newResumeContent[keys[0]] = value
            }
        })
        // 表单提交后更新数据
        resumeSave(newResumeContent)
    }

    const resumeInfoList = useMemo(()=>{
        const {
            sex,age,phone,presentAddress,email,nation,
            intendedPosition,intendedCity,intendedSalary,jobApplicationType,currentStatus
        } = detailPersonalMessage 

        return{
            // 基本信息
            'baseInformation': [
                {label:'性别：',name:'sex',contentValue:sex},
                {label:'年龄：',name:'age',contentValue:age},
                {label:'电话：',name:'phone',contentValue:phone},
                {label:'现所在地：',name:'presentAddress',contentValue:presentAddress},
                {label:'邮箱：',name:'email',contentValue:email},
                {label:'民族：',name:'nation',contentValue:nation}
            ],
            // 求职意向
            'jopIntention':[
                {label:'意向岗位：',name:'intendedPosition',contentValue:intendedPosition},
                {label:'意向城市：',name:'intendedCity',contentValue:intendedCity},
                {label:'期望薪资：',name:'intendedSalary',contentValue:intendedSalary},
                {label:'求职类型：',name:'jobApplicationType',contentValue:jobApplicationType},
                {label:'当前状态：',name:'currentStatus',contentValue:currentStatus},
            ]        
        }
    },[detailPersonalMessage])

    return(
        <div>
        <form method="post"  ref={contentForm} onSubmit={handleSubmit}>
            {resumeList.length>0 && id &&  (
                <>
                    <div className={home.resumeOperationBtn}>
                        {
                            !isEdit && <span onClick={resumeEdit}>编辑</span> ||
                            isEdit && <span onClick={cancelResumeEdit}>取消</span>
                        }
                        {
                            isEdit && <span onClick={()=>contentForm.current.requestSubmit()}>保存</span>
                        }
                    </div>

                    <div className={home.resumeContent}>
                        <div className={home.baseMessage}>
                            <div className={home.detail}>
                                {/* 基本信息 */}
                                <div className={home.name}>
                                    <ContentBox 
                                        name="name"
                                        label=""
                                        contentValue={detailPersonalMessage.name} 
                                        isEdit={isEdit}
                                    />
                                </div>
                                <ul>
                                    {resumeInfoList.baseInformation.map(item=>(
                                        <li key={item.name}>
                                            <ContentBox 
                                                name={item.name}
                                                label={item.label}
                                                contentValue={item.contentValue} 
                                                isEdit={isEdit}
                                            />
                                        </li>
                                    ))}
                                </ul>
                            </div>
                            <div>照片</div>
                        </div>
                        <div className={home.postioWish}>
                            <div className={home.title}>
                                求职意向
                            </div>
                            <ul>
                                { resumeInfoList.jopIntention.map(item=>(
                                    <li key={item.name}>
                                        <ContentBox 
                                            name={item.name}
                                            label={item.label}
                                            contentValue={item.contentValue} 
                                            isEdit={isEdit}
                                        />
                                    </li>
                                ))}
                            </ul>
                        </div>
                        
                        <div className={home.education}>
                            <div className={home.title}>
                                教育经历
                            </div>
                            <LoopEditModel 
                                modelValue = {detailPersonalMessage.educationExperience}
                                isEdit={isEdit}  
                                propertyAttr="educationExperience"
                            />
                        </div>
                        <div className={home.professionalSkill}>
                            <div className={home.title}>
                                专业技能
                            </div>
                            <LoopEditModel 
                                 modelValue = {detailPersonalMessage.professionalSkill}
                                isEdit={isEdit}  
                                propertyAttr="professionalSkill"
                            />
                        </div>
                        <div className={home.workExperience}>
                            <div className={home.title}>
                                工作经历
                            </div>
                            <LoopEditModel 
                                inputType='textarea'
                                modelValue = {detailPersonalMessage.workExperience}
                                isEdit={isEdit}  
                                propertyAttr="workExperience"
                            />
                        </div>
                        <div className={home.openProduct}>
                            <div className={home.title}>
                                开源项目及作品
                            </div>
                            <LoopEditModel 
                                inputType='textarea'
                                modelValue = {detailPersonalMessage.openProduct}
                                isEdit={isEdit}  
                                propertyAttr="openProduct"
                            />
                        </div>
                    </div>
                </>
            )}
            {/* 模板 */}
            {
                resumeList.length == 0 &&
                <div> 
                    暂无内容，请新增模板
                </div>
            }
        </form>
        </div>
    )
}